require('./index.css');

var $ = require('jquery');
var _common_util  = require('util/common_util.js');
var _user_service = require('service/user-service.js');

//错误信息的显示
var formError = {
    show : function(errMsg){
        $('.error-item1').show().find('.err-msg1').text(errMsg);
    },
    hide : function(){
        $('.error-item1').hide().find('.err-msg1').text('');
    }
};


var page = {
    init : function(){
        this.bindEvent();
    },
    bindEvent : function(){
        var _this = this;
        $('#submit').click(function(){
            _this.submit();
            console.log("register");
        })
    },
    submit : function(){
        var formData = {
            username : $.trim($('#username').val()),
            password : $.trim($('#password').val()),
            check_password : $.trim($('#check_password').val()),
            email : $.trim($('#email').val()),
            phone : $.trim($('#phone').val()),
            question : $.trim($('#question').val()),
            answer : $.trim($('#answer').val()),

        };

        var validationResult = this.formValidation(formData);
        if(validationResult.status){
            //提交后端进行注册
            _user_service.register(formData,function(res){
                window.location.href = _common_util.getURLParam('redirect') || './index.html';
            }, function(errMsg){
                formError.show(errMsg);
            });
        }else{
            //提示数据校验错误
            formError.show(validationResult.msg);
        }
    },
    formValidation : function(formData){
        var result = {
            status : false,
            msg    : ''
        };

        if(!_common_util.validate(formData.username,'require')){
            result.msg = '用户名不能为空';
            return result;
        }
        if(!_common_util.validate(formData.password,'require')){
            result.msg = '密码不能为空';
            return result;
        }
        if(!_common_util.validate(formData.check_password,'require')){
            result.msg = '确认密码不能为空';
            return result;
        }
        if(!_common_util.validate(formData.email,'require')){
            result.msg = '邮箱不能为空';
            return result;
        }
        if(!_common_util.validate(formData.phone,'require')){
            result.msg = '电话号码不能为空';
            return result;
        }
        if(!_common_util.validate(formData.question,'require')){
            result.msg = '安全问题不能为空';
            return result;
        }
        if(!_common_util.validate(formData.answer,'require')){
            result.msg = '安全答案不能为空';
            return result;
        }


        //验证通过
        result.status = true;
        result.msg = '验证通过';
        return result;
    }
};

$(function () {
    page.init();
});